package com.dh.leetcode.five;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName: _539_minimum_time_difference
 * @Description: 539. 最小时间差
 * 给定一个 24 小时制（小时:分钟 "HH:MM"）的时间列表，找出列表中任意两个时间的最小时间差并以分钟数表示。
 * <p>
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * 输入：timePoints = ["23:59","00:00"]
 * 输出：1
 * 示例 2：
 * <p>
 * 输入：timePoints = ["00:00","23:59","00:00"]
 * 输出：0
 * <p>
 * <p>
 * 提示：
 * <p>
 * 2 <= timePoints <= 2 * 104
 * timePoints[i] 格式为 "HH:MM"
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/minimum-time-difference
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 * @Author: shouzimu
 * @Date: 2022/1/18 10:42
 */
public class _539_minimum_time_difference {

    public int findMinDifference(List<String> timePoints) {
        Collections.sort(timePoints);
        int len = timePoints.size();
        int min = 1440 + getMin(timePoints.get(0)) - getMin(timePoints.get(len - 1));
        for (int i = 1; i < timePoints.size(); i++) {
            String c = timePoints.get(i);
            String p = timePoints.get(i - 1);
            ;
            int cm = getMin(c) - getMin(p);
            if (cm < min) {
                min = cm;
            }
            if (min == 0) {
                break;
            }
        }
        return min;
    }

    private int getMin(String t) {
        return ((t.charAt(0) - '0') * 10 + (t.charAt(1) - '0')) * 60 + (t.charAt(3) - '0') * 10 + (t.charAt(4) - '0');
    }

    @Test
    public void findMinDifferenceTest() {
        Assert.assertEquals(293, findMinDifference(Arrays.asList(new String[]{"14:49", "09:56", "01:02"})));
        Assert.assertEquals(120, findMinDifference(Arrays.asList(new String[]{"00:00", "04:00", "22:00"})));
        Assert.assertEquals(0, findMinDifference(Arrays.asList(new String[]{"00:00", "23:59", "00:00"})));
        Assert.assertEquals(1, findMinDifference(Arrays.asList(new String[]{"23:59", "00:00"})));
    }
}
